{% extends "base.html" %}

{% block title %}通知配置{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-bell me-2"></i>通知配置</h2>
                <button type="button" class="btn btn-primary" onclick="showAddConfigModal()">
                    <i class="fas fa-plus me-1"></i>新增配置
                </button>
            </div>

            <!-- 配置列表 -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>配置名称</th>
                                    <th>描述</th>
                                    <th>Webhook地址</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="configTableBody">
                                <!-- 配置列表将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增/编辑配置模态框 -->
<div class="modal fade" id="configModal" tabindex="-1" aria-labelledby="configModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="configModalLabel">新增通知配置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="configForm">
                    <input type="hidden" id="configId" name="id">
                    
                    <div class="mb-3">
                        <label for="configName" class="form-label">配置名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="configName" name="name" required>
                        <div class="form-text">为这个通知配置起一个便于识别的名称</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="configDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="configDescription" name="description" rows="2"></textarea>
                        <div class="form-text">可选，描述这个配置的用途</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="webhookUrl" class="form-label">钉钉机器人Webhook地址 <span class="text-danger">*</span></label>
                        <input type="url" class="form-control" id="webhookUrl" name="webhook_url" required>
                        <div class="form-text">
                            从钉钉群机器人设置中获取的Webhook地址<br>
                            格式：https://oapi.dingtalk.com/robot/send?access_token=xxx
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="secret" class="form-label">加签密钥</label>
                        <input type="text" class="form-control" id="secret" name="secret">
                        <div class="form-text">
                            可选，如果钉钉机器人启用了加签验证，请填入密钥<br>
                            在钉钉机器人安全设置中可以找到
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="isEnabled" name="is_enabled" checked>
                            <label class="form-check-label" for="isEnabled">
                                启用此配置
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveConfig()">保存</button>
                <button type="button" class="btn btn-success" onclick="testConfig()" id="testConfigBtn">
                    <i class="fas fa-paper-plane me-1"></i>测试发送
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除配置 "<span id="deleteConfigName"></span>" 吗？</p>
                <p class="text-danger">删除后无法恢复，使用此配置的任务将无法发送通知。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">删除</button>
            </div>
        </div>
    </div>
</div>

<script>
let currentConfigId = null;
let deleteConfigId = null;

// 页面加载时获取配置列表
document.addEventListener('DOMContentLoaded', function() {
    loadConfigs();
});

// 加载配置列表
function loadConfigs() {
    fetch('/api/notification-configs')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderConfigs(data.data);
            } else {
                showAlert('加载配置失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('加载配置失败', 'danger');
        });
}

// 渲染配置列表
function renderConfigs(configs) {
    const tbody = document.getElementById('configTableBody');
    tbody.innerHTML = '';
    
    if (configs.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无通知配置</td></tr>';
        return;
    }
    
    configs.forEach(config => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${escapeHtml(config.name)}</td>
            <td>${escapeHtml(config.description || '-')}</td>
            <td>
                <span class="text-muted" title="${escapeHtml(config.webhook_url)}">
                    ${config.webhook_url.substring(0, 50)}...
                </span>
            </td>
            <td>
                <span class="badge ${config.is_enabled ? 'bg-success' : 'bg-secondary'}">
                    ${config.is_enabled ? '已启用' : '已禁用'}
                </span>
            </td>
            <td>${formatDateTime(config.created_at)}</td>
            <td>
                <button class="btn btn-sm btn-outline-primary me-1" onclick="editConfig(${config.id})" title="编辑">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-outline-success me-1" onclick="testConfigById(${config.id})" title="测试发送">
                    <i class="fas fa-paper-plane"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="deleteConfig(${config.id}, '${escapeHtml(config.name)}')" title="删除">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 显示新增配置模态框
function showAddConfigModal() {
    currentConfigId = null;
    document.getElementById('configModalLabel').textContent = '新增通知配置';
    document.getElementById('configForm').reset();
    document.getElementById('configId').value = '';
    document.getElementById('isEnabled').checked = true;
    
    const modal = new bootstrap.Modal(document.getElementById('configModal'));
    modal.show();
}

// 编辑配置
function editConfig(id) {
    fetch(`/api/notification-configs/${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const config = data.data;
                currentConfigId = id;
                
                document.getElementById('configModalLabel').textContent = '编辑通知配置';
                document.getElementById('configId').value = config.id;
                document.getElementById('configName').value = config.name;
                document.getElementById('configDescription').value = config.description || '';
                document.getElementById('webhookUrl').value = config.webhook_url;
                document.getElementById('secret').value = config.secret || '';
                document.getElementById('isEnabled').checked = config.is_enabled;
                
                const modal = new bootstrap.Modal(document.getElementById('configModal'));
                modal.show();
            } else {
                showAlert('获取配置失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('获取配置失败', 'danger');
        });
}

// 保存配置
function saveConfig() {
    const form = document.getElementById('configForm');
    const formData = new FormData(form);
    
    // 处理复选框
    formData.set('is_enabled', document.getElementById('isEnabled').checked);
    
    const data = Object.fromEntries(formData.entries());
    
    const url = currentConfigId ? `/api/notification-configs/${currentConfigId}` : '/api/notification-configs';
    const method = currentConfigId ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(currentConfigId ? '配置更新成功' : '配置创建成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('configModal')).hide();
            loadConfigs();
        } else {
            showAlert('保存失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('保存失败', 'danger');
    });
}

// 测试配置
function testConfig() {
    const form = document.getElementById('configForm');
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    data.is_enabled = document.getElementById('isEnabled').checked;
    
    const testBtn = document.getElementById('testConfigBtn');
    const originalText = testBtn.innerHTML;
    testBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>发送中...';
    testBtn.disabled = true;
    
    fetch('/api/notification-configs/test', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('测试消息发送成功！', 'success');
        } else {
            showAlert('测试发送失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('测试发送失败', 'danger');
    })
    .finally(() => {
        testBtn.innerHTML = originalText;
        testBtn.disabled = false;
    });
}

// 通过ID测试配置
function testConfigById(id) {
    fetch(`/api/notification-configs/${id}/test`, {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('测试消息发送成功！', 'success');
        } else {
            showAlert('测试发送失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('测试发送失败', 'danger');
    });
}

// 删除配置
function deleteConfig(id, name) {
    deleteConfigId = id;
    document.getElementById('deleteConfigName').textContent = name;
    
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}

// 确认删除
function confirmDelete() {
    fetch(`/api/notification-configs/${deleteConfigId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('配置删除成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
            loadConfigs();
        } else {
            showAlert('删除失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('删除失败', 'danger');
    });
}

// 工具函数
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatDateTime(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

function showAlert(message, type) {
    // 创建alert元素
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 3000);
}
</script>
{% endblock %}